//package org.chs.ts.batch.job;
//
//
//import com.alibaba.fastjson.JSONException;
//import com.alibaba.fastjson.JSONObject;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.logging.log4j.util.Strings;
//import org.chs.ts.batch.controller.BatchExecController;
//import org.chs.ts.batch.exception.TaskExecException;
//import org.chs.ts.batch.factory.TaskExecFactory;
//import org.chs.ts.batch.log.entity.BatchClearBasicLog;
//import org.chs.ts.batch.service.IBatchClearBasicGroupInfoSetService;
//import org.chs.ts.batch.service.IBatchClearBasicLogService;
//import org.chs.ts.batch.set.entity.BatchClearBasicGroupInfoSet;
//import org.chs.ts.batch.threadservice.BatchExecAsyncService;
//import org.chs.ts.batch.util.CommonUtil;
//import org.chs.ts.batch.util.ParameterUtil;
//import org.chs.ts.base.batch.vo.entity.BatchExecReq;
//import org.chs.ts.main.common.exception.ServiceException;
//import org.chs.ts.main.common.util.RedissonLockService;
//import org.chs.ts.main.common.util.oConvertUtils;
//import org.chs.ts.base.constant.CommonConstant;
//import org.springframework.core.env.Environment;
//import org.springframework.scheduling.annotation.Scheduled;
//
//import javax.annotation.Resource;
//import java.math.BigDecimal;
//import java.text.SimpleDateFormat;
//import java.util.Date;
//import java.util.List;
//import java.util.Locale;
//import java.util.concurrent.atomic.AtomicLong;
//
///**
// * @Compay 盛唐天行
// * @Author: wuwei
// * @Censor By wuwei
// * @Sence 2023/12/19 11:15
// * @Modify 2023/12/19 11:15
// * @Description 定时跑批job 异步多线程(线程池)执行 与 BatchTaskScheduled 不能同时开启
// */
////@EnableScheduling
////@Component
//@Slf4j
//public class BatchTaskAsyncScheduled {
//    @Resource
//    private TaskExecFactory taskExecFactory;
//
//    @Resource
//    private RedissonLockService redissonLockService;
//    @Resource
//    private BatchExecController batchExecController;
//    @Resource
//    private ParameterUtil parameterUtil;
//    @Resource
//    private Environment environment;
//    @Resource
//    private IBatchClearBasicGroupInfoSetService clearBasicGroupInfoService;
//    @Resource
//    private IBatchClearBasicLogService clearBasicLogService;
//
//    @Resource
//    private BatchExecAsyncService batchExecAsyncService;
//
//
//    private String batchSysCode;
//    private String taskGroup;
//    private String execDate;
//    private String snatchingMode;
//
//    // private final AtomicLong MAX_ERROR_COUNT = new AtomicLong(5);
//    private final AtomicLong MAX_WAITTING_TIME = new AtomicLong(5000);
//
//    // 每小时 00分05秒 30分05秒 执行
//    @Scheduled(cron = "30 1,10,20,30,40,50,58 * * * ?")
//    public void process() {
//        String key = "BatchTaskScheduled";
//
//        threadSleepRandom();
//
//        try {
//           // redissonLockService.dealLockAndUnlock(key, () -> {
//                boolean isGetWaitting = false;
//                log.info("-------------------------------" + CommonUtil.getLocalHostAddress() + " -> BatchTaskAsyncScheduled 执行日志" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//
//                // 线程池控制
//                try {
//                    taskExecFactory.checkThreadPool();
//                } catch (TaskExecException e) {
//                    log.info("-------------------------------" + CommonUtil.getLocalHostAddress() + " -> BatchTaskAsyncScheduled 执行日志" + e.getMessage());
//                    return;
//
//                }
//
//                // 获取 待执行 列表
//                List<BatchClearBasicGroupInfoSet> taskGroupList = initParameter();
//                for (BatchClearBasicGroupInfoSet taskGroup : taskGroupList) {
//                    // 获取参数
//                    String runningTime = getGroupInfoParameter(taskGroup.getTaskGroup(), taskGroup.getPreTaskParameter(), "runningTime");
//                    String diffDate = getGroupInfoParameter(taskGroup.getTaskGroup(), taskGroup.getPreTaskParameter(), "diffDate");
//                    boolean isRestrictExecTime = getGroupInfoTypeOfBoolean(taskGroup.getTaskGroup(), taskGroup.getPreTaskParameter(), "isRestrictExecTime");
//                    // 增加执行时间限制
//                    if (isRestrictExecTime) {
//                        if (!(checkCurrentTime(runningTime))) {
//                            log.info("BatchTaskAsyncScheduled 执行日志-跑批组未在可执行时间 taskGroup -> [" + taskGroup.getTaskGroup() + "] execDate -> [" + this.execDate + "]" + " runningTime -> [" + runningTime + "]" + "diffDate -> [" + diffDate + "]isRestrictExecTime -> [" + isRestrictExecTime + "]" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//                            //createClearBasicLog(false, "BatchTaskScheduled 执行日志-跑批组未在可执行时间 taskGroup -> [" + this.taskGroup + "] execDate -> [" + this.execDate + "] snatchingMode -> [" + this.snatchingMode + "]" + " runningTime -> [" + runningTime + "]" + " isRestrictExecTime -> [" + isRestrictExecTime + "]" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), "");
//                            continue;
//                        }
//                    }
//
//                    //createClearBasicLog(true, "BatchTaskScheduled 执行日志-跑批组在可执行时间,准备获取可执行列表 taskGroup -> [" + this.taskGroup + "] execDate -> [" + this.execDate + "] snatchingMode -> [" + this.snatchingMode + "]" + " runningTime -> [" + runningTime + "]" + " isRestrictExecTime -> [" + isRestrictExecTime + "]" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), "");
//                    log.info("BatchTaskAsyncScheduled 执行日志-跑批组在可执行时间，准备获取可执行列表 taskGroup -> [" + taskGroup.getTaskGroup() + "] execDate -> [" + this.execDate + "]" + " runningTime -> [" + runningTime + "]" + "diffDate -> [" + diffDate + "]isRestrictExecTime -> [" + isRestrictExecTime + "]" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//
//                    // 根据 获取 有效 taskgroupID
//                    BatchExecReq taskWaittingList = batchExecController.getTaskWaittingList(taskGroup.getBatchSysCode(),taskGroup.getTaskGroup(), this.execDate);
//                    if (taskWaittingList == null || taskWaittingList.getTaskGroup() == null) {
//                        // 未获取待执行跑批计划列表
//                        log.info("BatchTaskAsyncScheduled 执行日志-跑批组在可执行时间，未获取可执行列表 taskGroup -> [" + taskGroup.getTaskGroup() + "] execDate -> [" + this.execDate + "]" + " runningTime -> [" + runningTime + "]" + "diffDate -> [" + diffDate + "]isRestrictExecTime -> [" + isRestrictExecTime + "]" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//                        continue;
//                    }
//                    this.batchSysCode = taskWaittingList.getBatchSysCode();
//                    this.taskGroup = taskWaittingList.getTaskGroup();
//                    this.snatchingMode = taskWaittingList.getSnatchingMode();
//                    // 确认当前跑批列表
//                    isGetWaitting = batchExecController.confirmTaskWaitting(this.batchSysCode,this.taskGroup, this.execDate, this.snatchingMode);
//                    if (isGetWaitting) {
//                        log.info("BatchTaskAsyncScheduled 执行日志-跑批组在可执行时间，确认跑批列表成功！ taskGroup -> [" + taskGroup.getTaskGroup() + "] execDate -> [" + this.execDate + "]" + " runningTime -> [" + runningTime + "]" + "diffDate -> [" + diffDate + "]isRestrictExecTime -> [" + isRestrictExecTime + "]" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//                        createClearBasicLog(true, "BatchTaskScheduled 执行日志-跑批组在可执行时间，确认跑批列表成功 taskGroup -> [" + this.taskGroup + "] execDate -> [" + this.execDate + "] snatchingMode -> [" + this.snatchingMode + "]" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), "");
//                        break;
//                    } else {
//                        log.info("BatchTaskAsyncScheduled 执行日志-跑批组在可执行时间，跑批组在可执行时间，确认跑批列表失败！ taskGroup -> [" + taskGroup.getTaskGroup() + "] execDate -> [" + this.execDate + "]" + " runningTime -> [" + runningTime + "]" + "diffDate -> [" + diffDate + "]isRestrictExecTime -> [" + isRestrictExecTime + "]" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//                        createClearBasicLog(false, "BatchTaskScheduled 执行日志-跑批组在可执行时间，跑批组在可执行时间，确认跑批列表失败！ taskGroup -> [" + taskGroup.getTaskGroup() + "] execDate -> [" + this.execDate + "]" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), "");
//                    }
//
//
//                }
//                if (isGetWaitting) {
//                    // 获取 当前待执行 taskGroup 信息 准备后续 进行执行
//                    // new Thread(new ProcessTask(this.taskGroup, this.execDate, this.snatchingMode)).start();
//                    batchExecAsyncService.asyncDoJob(this.batchSysCode,this.taskGroup, this.execDate, this.snatchingMode);
//                }
//
//           // }, new ServiceException(RetCode.FAILED, "未能获取锁，等待下次重新获取"));
//        } catch (ServiceException e) {
//            log.info(e.getMessage());
//        }
//
//    }
//
//
//    /**
//     * 线程随机等待
//     */
//    private void threadSleepRandom() {
//        long waitTime = (long) (Math.random() * 2 * MAX_WAITTING_TIME.get());
//        try {
//            Thread.sleep(waitTime);
//        } catch (InterruptedException e) {
//            //e.printStackTrace();
//        }
//
//        log.info("-------------------------------" + CommonUtil.getLocalHostAddress() + " -> 抢夺等待时间:" + waitTime + "毫秒！当前时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//    }
//
//
//    /**
//     * 验证当前时间 是否可执行跑批操作
//     *
//     * @param cut_time 系统参数 日切时间
//     * @return boolean
//     * @Description 先解析小时，确认小时是否符合
//     */
//    private Boolean checkCurrentTime(String cut_time) {
//        Date current_datatime = new Date();
//        String sys_current_time = new SimpleDateFormat("HH:mm:ss").format(current_datatime);
//        String[] sys_current_time_split = sys_current_time.split(":");
//        String[] cut_time_split = cut_time.split(":");
//
//        String sys_current_hour = sys_current_time_split[0];
//        String cut_hour = cut_time_split[0];
//        // 当前 时 不一致
//        if (!sys_current_hour.equals(cut_hour)) {
//            return false;
//        }
//
//        // 判断当前时间
//        BigDecimal cut_time_decimal = new BigDecimal(cut_time_split[1] + cut_time_split[2]);
//        BigDecimal sys_current_time_decimal = new BigDecimal(sys_current_time_split[1] + sys_current_time_split[2]);
//        // 当前时间 大于 指定 日切时间
//        return sys_current_time_decimal.compareTo(cut_time_decimal) >= 0;
//    }
//
//
//    /**
//     * 初始化参数
//     */
//    private List<BatchClearBasicGroupInfoSet> initParameter() {
//        this.execDate = parameterUtil.getParameterByCode(ParamConstant.LAST_DAY);
//        this.taskGroup = "";
//        this.snatchingMode = "";
//        return clearBasicGroupInfoService.getAvailabilityGroupInfo();
//
//    }
//
//    private boolean getGroupInfoTypeOfBoolean(String taskGroup, String preTaskParameter, String key) {
//        boolean result = false;
//        String result_str = getGroupInfoParameter(taskGroup, preTaskParameter, key);
//
//        if (!Strings.isBlank(result_str)) {
//            result = Boolean.parseBoolean(result_str);
//        }
//
//        return result;
//    }
//
//    private String getGroupInfoParameter(String taskGroup, String preTaskParameter, String key) {
//        String logSernoPrdfix = "groupInfoParameter";
//        String returnValue = "";
//        if (Strings.isBlank(preTaskParameter) || preTaskParameter.equals("{}")) {
//            createClearBasicLog(false, "获取跑批组参数为空! taskGroup -> " + taskGroup + " preTaskParameter -> " + preTaskParameter, "", logSernoPrdfix);
//            log.info("getGroupInfoParameter:获取跑批组参数异常  获取跑批组参数为空! taskGroup -> " + taskGroup + " preTaskParameter -> " + preTaskParameter + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//        } else {
//            try {
//                JSONObject parameter = JSONObject.parseObject(preTaskParameter);
//                if (parameter.containsValue(key)) {
//                    createClearBasicLog(false, "获取跑批组参数key不存在! taskGroup -> " + taskGroup + " preTaskParameter -> " + preTaskParameter + " key -> " + key, "", logSernoPrdfix);
//                    log.info("getGroupInfoParameter:获取跑批组参数异常  获取跑批组参数key不存在! taskGroup -> " + taskGroup + " preTaskParameter -> " + preTaskParameter + " key -> " + key + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//                }
//                returnValue = parameter.getString(key);
//            } catch (JSONException e) {
//                createClearBasicLog(false, "获取跑批组参数异常! taskGroup -> " + taskGroup + " preTaskParameter -> " + preTaskParameter + " " + e.getMessage(), "", logSernoPrdfix);
//                log.info("getGroupInfoParameter:获取跑批组参数异常  获取跑批组参数异常! taskGroup -> " + taskGroup + " preTaskParameter -> " + preTaskParameter + " " + e.getMessage() + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//            }
//        }
//        return returnValue;
//    }
//
//    private void createClearBasicLog(boolean runningResult, String errMsg, String currentDate, String logSernoPrdfix) {
//        if (logSernoPrdfix.length() > 19) {
//            logSernoPrdfix = logSernoPrdfix.substring(0, 19);
//            log.error("createClearBasicLog -> logSernoPrdfix参数过长请及时调整，参数长度应小于等于1位： " + logSernoPrdfix + "[" + logSernoPrdfix.length() + "]");
//        }
//        currentDate = currentDate.equals("") ? new SimpleDateFormat("yyyyMMdd").format(new Date()) : currentDate;
//        String ip = CommonUtil.getLocalHostAddress();
//        String port = environment.getProperty("server.port");
//        String path = oConvertUtils.getString(environment.getProperty("server.servlet.context-path"));
//
//        BatchClearBasicLog clearBasicLog = new BatchClearBasicLog();
//        clearBasicLog.setSysOrgCode("");//所属部门
//        clearBasicLog.setLogSerno(logSernoPrdfix.toUpperCase(Locale.ROOT) + System.currentTimeMillis());//日志号
//        clearBasicLog.setTaskDate(currentDate);//清算业务日期
//        clearBasicLog.setExecStatus(runningResult ? "3" : "4");//执行状态 (0-未执行; 1-占用中; 2-执行中;   3-执行成功; 4-执行失败; 5-跳过执行; 6-任务终止; )
//        clearBasicLog.setExecDate(currentDate);//执行日期
//        clearBasicLog.setShouldExecDate(currentDate);//应执行日期
//        clearBasicLog.setServerName(path);//服务器主机名
//        clearBasicLog.setServerIp(ip + ":" + port);//服务器IP
//        clearBasicLog.setRtnCode(runningResult ? CommonConstant.RTN_CODE_SUCCESS : CommonConstant.RTN_CODE_FAILED);//返回码
//        clearBasicLog.setRtnDesc(errMsg);//执行结束信息
//
//        clearBasicLogService.save(clearBasicLog);
//
//    }
//
//    private void createClearBasicLog(boolean runningResult, String errMsg, String currentDate) {
//        String logSernoPrdfix = "BatchTaskScheduled";
//        createClearBasicLog(runningResult, errMsg, currentDate, logSernoPrdfix);
//    }
//}
